//    Copyright (C) 2013  <lugocreation@gmail.com>
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.
package org.jpgolay.me.db;

import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.*;
import javax.swing.*;
import org.jpgolay.gui.fixed.BasicMenu;
import org.jpgolay.gui.iconBar.*;
import org.jpgolay.me.persistence.ObjectServiceCRUD;
import org.jpgolay.me.persistence.UtilityDB;
import org.jpgolay.me.util.*;

// Referenced classes of package org.jpgolay.me.db:
//            DbGUI, Db
public class DbController extends DbGUI {

    public DbController(Parameter param) {
        create = false;
        write = false;
        this.param = param;
        crud = new ObjectServiceCRUD();
        initLaw();
        initMenu();
        initIconBar();
        initField();
        initCompanyList();
    }

    private void initLaw() {
        if (param.getAccessLaw().length() >= 1 && param.getAccessLaw().charAt(1) == '1') {
            write = true;
        }
    }

    private void initMenu() {
        getMenuPanel().getExit().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionExit();
            }
        });
        getMenuPanel().getDelete().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionDelete();
            }
        });
        getMenuPanel().getHelp().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionHelp();
            }
        });
        getMenuPanel().getModify().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionModify();
            }
        });
        getMenuPanel().getNew().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionNew();
            }
        });
        getMenuPanel().getOpen().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent actionevent) {
            }
        });
        getMenuPanel().getPrint().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionPrint();
            }
        });
        getMenuPanel().getSave().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionSave();
            }
        });
    }

    private void initIconBar() {
        getIconBarPanel().addAnswerListener(new AnswerListener() {
            public void create(AnswerEvent e) {
                actionNew();
            }

            public void open(AnswerEvent answerevent) {
            }

            public void modify(AnswerEvent e) {
                actionModify();
            }

            public void save(AnswerEvent e) {
                actionSave();
            }

            public void remove(AnswerEvent e) {
                actionDelete();
            }

            public void print(AnswerEvent e) {
                actionPrint();
            }

            public void help(AnswerEvent e) {
                actionHelp();
            }
        });
    }

    private void initField() {
        cleanField();
        setEnabledField(false);
        getIconBarPanel().setEnabledCreate(write);
        getIconBarPanel().setEnabledSave(false);
        getIconBarPanel().setEnabledModify(false);
        getIconBarPanel().setEnabledRemove(false);
        getIconBarPanel().setEnabledPrint(false);
        getIconBarPanel().setEnabledOpen(false);
        getMenuPanel().getNew().setEnabled(write);
        getMenuPanel().getSave().setEnabled(false);
        getMenuPanel().getModify().setEnabled(false);
        getMenuPanel().getDelete().setEnabled(false);
        getMenuPanel().getPrint().setEnabled(false);
        getMenuPanel().getOpen().setEnabled(false);
        create = false;
    }

    private void initCompanyList() {
        java.util.Collection c = crud.readAll(null, 51);
        if (c != null) {
            Db db = null;
            companyList = new ArrayList(c);
            Iterator it = companyList.iterator();
            String list[] = new String[companyList.size()];
            for (int i = 0; it.hasNext(); i++) {
                db = (Db) it.next();
                list[i] = db.getName();
            }

            setCompanyListValue(list);
            getCompanyListComboBox().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    actionLoadCompany(getCompanyListComboBox().getSelectedIndex());
                }
            });
        } else {
            setCompanyListValue(new String[]{
                        "aucune"
                    });
        }
    }

    private void actionExit() {
        setVisible(false);
    }

    private void actionDelete() {
        int reponse = JOptionPane.showConfirmDialog(null, "Etes-vous certain de vouloir suprimer cette Soci\351t\351 ?", "Confirmation", 1, 2, null);
        switch (reponse) {
            case 0: // '\0'
                actionDeleteCompany();
            // fall through

            case -1:
            case 1: // '\001'
            case 2: // '\002'
            default:
                return;
        }
    }

    private void actionHelp() {
        BrowserControl.displayURL("www.media-4-u.net");
    }

    private void actionModify() {
        setEnabledField(true);
        getIconBarPanel().setEnabledCreate(false);
        getIconBarPanel().setEnabledSave(true);
        getIconBarPanel().setEnabledModify(false);
        getIconBarPanel().setEnabledRemove(true);
        getMenuPanel().getNew().setEnabled(false);
        getMenuPanel().getSave().setEnabled(true);
        getMenuPanel().getModify().setEnabled(false);
        getMenuPanel().getDelete().setEnabled(true);
    }

    private void actionNew() {
        initField();
        setEnabledField(true);
        setNameValue("Company");
        setDbnameValue("mydb");
        setUrlValue("jdbc:mysql://127.0.0.1:3306/mydb");
        setLoginValue("username");
        setPasswordValue("password");
        setAdminUrlValue("jdbc:mysql://127.0.0.1:3306/mysql");
        setAdminLoginValue("admin");
        setAdminPasswordValue("admindb");
        getIconBarPanel().setEnabledCreate(false);
        getIconBarPanel().setEnabledSave(true);
        getMenuPanel().getNew().setEnabled(false);
        getMenuPanel().getSave().setEnabled(true);
        create = true;
    }

    private void actionPrint() {
    }

    private void actionSave() {
        setCursor(new Cursor(3));
        if (create) {
            actionCreateCompany();
        } else {
            actionUpdateCompany();
        }
        setCursor(new Cursor(0));
    }

    private void actionLoadCompany(int index) {
        Db db = (Db) companyList.get(index);
        initField();
        setNameValue(db.getName());
        setDbnameValue(db.getDbname());
        setUrlValue(db.getUrl());
        setLoginValue(db.getLogin());
        setPasswordValue(db.getPassword());
        setAdminUrlValue(db.getAdminUrl());
        setAdminLoginValue(db.getAdminLogin());
        setAdminPasswordValue(db.getAdminPassword());
        setNotesValue(db.getNotes());
        setDateValue(db.getDate());
        setLastUpdateValue(db.getUpdateLastTime());
        setLastUserValue(db.getUpdateLastUserId());
        getIconBarPanel().setEnabledModify(write);
        getIconBarPanel().setEnabledPrint(true);
        getMenuPanel().getModify().setEnabled(write);
        getMenuPanel().getPrint().setEnabled(true);
    }

    private void actionUpdateCompany() {
        if (verifyRequirement()) {
            Db db = (Db) companyList.get(getCompanyListComboBox().getSelectedIndex());
            db.setName(getNameValue());
            db.setDbname(getDbnameValue());
            db.setUrl(getUrlValue());
            db.setLogin(getLoginValue());
            db.setPassword(getPasswordValue());
            db.setAdminUrl(getAdminUrlValue());
            db.setAdminLogin(getAdminLoginValue());
            db.setAdminPassword(getAdminPasswordValue());
            db.setNotes(getNotesValue());
            db.setUpdateLastUserId(param.getUserId());
            crud.update(db, 51);
            updatePropertie(db);
            initField();
            initCompanyList();
        }
    }

    private void actionCreateCompany() {
        if (verifyRequirement()) {
            Integer pk = (Integer) crud.create(51, null);
            if (pk != null) {
                Db db = (Db) crud.read(pk, 51);
                if (db != null) {
                    db.setName(getNameValue());
                    db.setDbname(getDbnameValue());
                    db.setUrl(getUrlValue());
                    db.setLogin(getLoginValue());
                    db.setPassword(getPasswordValue());
                    db.setAdminUrl(getAdminUrlValue());
                    db.setAdminLogin(getAdminLoginValue());
                    db.setAdminPassword(getAdminPasswordValue());
                    db.setNotes(getNotesValue());
                    db.setUpdateLastUserId(param.getUserId());
                    db.setDate((new MEDate()).getPlain());
                    crud.update(db, 51);
                    updatePropertie(db);
                    initField();
                    initCompanyList();
                } else {
                    initField();
                    JOptionPane.showMessageDialog(null, "Impossible d'enregistrer cette soci\351t\351 !");
                }
            } else {
                initField();
                JOptionPane.showMessageDialog(null, "Impossible d'enregistrer cette soci\351t\351 !");
            }
        }
    }

    private void updatePropertie(Db db) {
        Properties p = new Properties();
        try {
            FileInputStream fis = new FileInputStream("lib/me.properties");
            p.load(fis);
            p.setProperty("serial", db.getId().toString());
            p.setProperty("url", db.getUrl());
            p.setProperty("first_url", db.getAdminUrl());
            p.setProperty("pass", db.getPassword());
            p.setProperty("user", db.getLogin());
            p.setProperty("first_user", db.getAdminLogin());
            p.setProperty("first_pass", db.getAdminPassword());
            p.setProperty("database_home", db.getDbname());
            p.store(new FileOutputStream("lib/me.properties"), "ME properties file db connection");
            if (create) {
                createDB();
            }
            JOptionPane.showMessageDialog(null, "Les parametres ont \351t\351 enregistr\351 avec succ\351s !\n\nPour vous connecter sur la soci\351t\351 vous devez\nquitter JGestCom et relancer JGestCom.\n(Si c'est une nouvelle soci\351t\351 il faut\nse connecter comme administrateur pour\nfinaliser le parametrage)");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e1) {
            System.out.println("error Saving properties file: " + e1);
        }
    }

    private void createDB() {
        UtilityDB udb = new UtilityDB();
        udb.createDefaultMysqlDB(companyList);
    }

    private void actionDeleteCompany() {
        Db db = (Db) companyList.get(getCompanyListComboBox().getSelectedIndex());
        crud.delete(db.getId(), db.getUpdateLastTime(), 51);
        initField();
        initCompanyList();
    }

    private boolean verifyRequirement() {
        if (getNameValue() != null && getNameValue().length() < 1) {
            JOptionPane.showMessageDialog(null, "Nom de la soci\351t\351 obligatoire !");
            return false;
        }
        if (getNameValue() == null) {
            JOptionPane.showMessageDialog(null, "Nom de la soci\351t\351 obligatoire !");
            return false;
        }
        if (getNameValue() != null && getNameValue().length() > 50) {
            JOptionPane.showMessageDialog(null, "Nom de la soci\351t\351 trop long !\n(maximum 50 carat\350res)");
            return false;
        }
        if (getDbnameValue() != null && getDbnameValue().length() > 50) {
            JOptionPane.showMessageDialog(null, "Nom de la base de donn\351e trop longue !\n(maximum 50 carat\350res)");
            return false;
        }
        if (getLoginValue() != null && getLoginValue().length() > 50) {
            JOptionPane.showMessageDialog(null, "Login trop long !\n(maximum 50 carat\350res)");
            return false;
        }
        if (getPasswordValue() != null && getPasswordValue().length() > 50) {
            JOptionPane.showMessageDialog(null, "Password trop long !\n(maximum 50 carat\350res)");
            return false;
        }
        if (getUrlValue() != null && getUrlValue().length() > 100) {
            JOptionPane.showMessageDialog(null, "URL trop longue !\n(maximum 100 carat\350res)");
            return false;
        }
        if (getAdminUrlValue() != null && getAdminUrlValue().length() > 100) {
            JOptionPane.showMessageDialog(null, "Admin URL trop longue !\n(maximum 100 carat\350res)");
            return false;
        }
        if (getAdminLoginValue() != null && getAdminLoginValue().length() > 50) {
            JOptionPane.showMessageDialog(null, "Admin Login trop long !\n(maximum 50 carat\350res)");
            return false;
        }
        if (getAdminPasswordValue() != null && getAdminPasswordValue().length() > 50) {
            JOptionPane.showMessageDialog(null, "Admin Password trop long !\n(maximum 50 carat\350res)");
            return false;
        }
        if (getNotesValue() != null && getNotesValue().length() > 100) {
            JOptionPane.showMessageDialog(null, "Notes trop longue !\n(maximum 100 carat\350res)");
            return false;
        } else {
            return true;
        }
    }
    private ObjectServiceCRUD crud;
    private Parameter param;
    private boolean create;
    private ArrayList companyList;
    private boolean write;
}
